package com.pro.common.modules.service.dependencies.upload.test;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.MinioException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class MinioUploadExample {

    public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeyException {
        String minioEndpoint = "http://127.0.0.1:9000"; // MinIO endpoint
        String bucketName = "config"; // Bucket name
        String objectName = "1_upload.png"; // Object name (file name on MinIO)
        String accessKey = "minioadmin"; // Access key
        String secretKey = "minioadmin"; // Secret key
        File file = new File("C:/1.png"); // Local file to upload

        uploadFile(minioEndpoint, bucketName, objectName, accessKey, secretKey, file);
        System.out.println("File uploaded successfully");
    }

    public static void uploadFile(String minioEndpoint, String bucketName, String objectName,
                                   String accessKey, String secretKey, File file) {
        try {
            // Initialize MinioClient with provided details
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioEndpoint)
                    .credentials(accessKey, secretKey)
                    .build();

            // Create FileInputStream for the file
            FileInputStream fileInputStream = new FileInputStream(file);

            // Upload file to MinIO server
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName) // Bucket name
                            .object(objectName) // Object (file) name on MinIO
                            .stream(fileInputStream, file.length(), -1) // Stream and file length
                            .build());

            // Close FileInputStream
            fileInputStream.close();

        } catch (MinioException e) {
            System.err.println("MinioException: " + e);
        } catch (IOException e) {
            System.err.println("IOException: " + e);
        } catch (NoSuchAlgorithmException e) {
            System.err.println("NoSuchAlgorithmException: " + e);
        } catch (InvalidKeyException e) {
            System.err.println("InvalidKeyException: " + e);
        }
    }
}
